package com.totoro.controller;

import com.totoro.pojo.Category;
import com.totoro.pojo.Product;
import com.totoro.pojo.SearchTextList;
import com.totoro.service.CategoryService;
import com.totoro.service.ProductService;
import com.totoro.service.ShopService;
import com.totoro.service.StatisticsService;
import com.totoro.utils.IKParticiple;
import com.totoro.utils.ReturnFormat;
import com.totoro.utils.TotoroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @author TOTORO
 * @date 2021/7/12 15:27
 * 搜索控制器
 */
@Controller
public class SearchController {

    @Autowired
    ProductService productService;
    @Autowired
    StatisticsService statisticsService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    ShopService shopService;

    /**
     * 搜索
     * @param enter
     * @param model
     * @return
     */
    @RequestMapping("/search_product")
    public String search(@RequestParam("enter") String enter,
                         @RequestParam(value = "cat", defaultValue = "0", required = false) int categoryId,
                         @RequestParam(value = "sort", defaultValue = "", required = false) String sort,
                         @RequestParam(value = "lowPrice", required = false, defaultValue = "0") double lowPrice,
                         @RequestParam(value = "highPrice", required = false, defaultValue = "100000000") double highPrice,
                         @RequestParam(value = "discount", defaultValue = "false", required = false) boolean isDiscount,
                         @RequestParam(value =  "curr", defaultValue = "0", required = false) int curr,
                         Model model){
        // (添加一条,改变次数) -> {关键字搜索率}
        SearchTextList searchTextList = statisticsService.findSeachTextCol(enter);
        if(null == searchTextList){
            statisticsService.addSearchText(new SearchTextList(0, enter, 1));
        } else{
            statisticsService.updateSearchTextCount(searchTextList.getId());
        }
        model.addAttribute("enter", enter);
        /// 先根据搜索的内容找一遍，如果找到了，就展示，如果没找到，则用分词器查找
        List<Product> firstList = productService.findProductsByName(enter, null, false, 0, 0, 100000000, 0);
        String[] splits = IKParticiple.participle(enter, false);
        if(firstList.size() > 0){
            String sql = "";
            switch (sort) {
                case "hot" :
                    sql = "p.click_count desc";
                    break;
                case "new":
                    sql = "p.create_time desc";
                    break;
                case "deal":
                    sql = "p.deal_count desc";
                    break;
                case "priceDesc":
                    sql = "p.product_now_price desc";
                    break;
                case "priceAsc":
                    sql = "p.product_now_price asc";
                    break;
            }
            // 未添加条件查找到的商品数量
            model.addAttribute("notTermProductCount", firstList.size());
            // 查找条件版本
            List<Product> termList = productService.findProductsByName(enter, sql, isDiscount, curr, lowPrice, highPrice, categoryId);
            // 未分页版本，效率会很慢，请勿模仿
            List<Product> notPagination = productService.findProductsByName(enter, sql, isDiscount, 0, lowPrice, highPrice, categoryId);
            // 查找这些商品的分类，如果此次的条件查询到了商品才继续
            if(notPagination.size() > 0) {
                Integer[] integers = new Integer[notPagination.size()];
                for (int i = 0; i < notPagination.size(); i++) {
                    integers[i] = notPagination.get(i).getBelongCategoryId();
                }

                // 获得去重后的所有分类
                Set<Integer> set = new HashSet();
                for (int i = 0; i < integers.length; i++) {
                    set.add(integers[i]);
                }
                Integer[] categoryIds = new Integer[set.size()];
                int index = 0;
                for (int i : set) {
                    categoryIds[index] = i;
                    index++;
                }
                List<Category> categories = categoryService.findCategoryByCategoryIds(categoryIds);
                // 最多十条分类
                if(categories.size() > 10){
                    categories.subList(0, 10);
                }
                model.addAttribute("categories", categories);
            }
            // 判断用户是否选择了分类
            if(categoryId !=0){
                Category category = categoryService.byIdFindCategory(categoryId);
                model.addAttribute("selectedCategory", category);
            }
            model.addAttribute("products", termList);
            model.addAttribute("isSplit", false);
            model.addAttribute("allCount", notPagination.size());
        } else {
            Map<String, List<Product>> map = new HashMap<>();
            // 拥有产品的关键字
            List<String> primarySplits = new ArrayList<>();
            for (int i = 0; i < splits.length; i++) {
                List<Product> list = productService.findProductsByName(splits[i], null, false, 0, 0, 100000000, 0);
                if (list.size() > 0) {
                    primarySplits.add(splits[i]);
                    map.put(splits[i], list);
                }
            }
            // 带参数跳转至商品列表页面
            model.addAttribute("productMap", map);
            model.addAttribute("primarySplits", primarySplits);
            model.addAttribute("splits", splits);
            model.addAttribute("isSplit", true);
            model.addAttribute("splitStatus", map.size()>0?true:false);
        }
        // 从搜索词库里查询与本次查询相关的词语
        List<SearchTextList> textLists = productService.findSearchText(splits);
        for (SearchTextList textList : textLists) {
            System.out.println(textList.getText());
        }
        model.addAttribute("textLists", textLists);
        // 掌柜热卖，寻找随机五个店铺，随机五个商品进行渲染
        List<Product> sellerHotProduct = shopService.findShopMaxDealProduct();
        model.addAttribute("sellerHotProduct", sellerHotProduct);
        return "product_search";
//        return "include/product/search";
    }

    @RequestMapping("/searchReturn")
    @ResponseBody
    public String searchReturn(@RequestParam("value") String value){
        List<SearchTextList> searchTextLists = productService.findReturn(value);
        return ReturnFormat.retData(searchTextLists, true);
    }

}
